package Search;

import Data.MassageData;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class SearchMassage {
    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";
    private MassageData massageData;

    public SearchMassage(MassageData massageData) {
        this.massageData = massageData;
    }

    public ArrayList<MassageData> LoadMassage() throws ClassNotFoundException, SQLException {
        ArrayList<MassageData> massagelist=new ArrayList<>();
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection Conn = DriverManager.getConnection(url, user, password);
        String sql = "SELECT *FROM massagelist WHERE (sender_id=? and receiver_id=?)or (sender_id=? and receiver_id=?) ORDER BY date DESC limit 20 OFFSET ?;";
        PreparedStatement operation = null;
        operation=Conn.prepareStatement(sql);
        operation.setString(1,massageData.getSender());
        operation.setString(2,massageData.getReceiver());
        operation.setString(3,massageData.getReceiver());
        operation.setString(4,massageData.getSender());
        operation.setInt(5,massageData.getSum());
        ResultSet resultSet=operation.executeQuery();
        while(resultSet.next())
        {
            MassageData e=new MassageData();
            e.setSender(resultSet.getString("sender_id"));
            e.setReceiver(resultSet.getString("receiver_id"));
            e.setTimestamp(resultSet.getTimestamp("date"));
            e.setContent(resultSet.getString("content"));
            int is_file=resultSet.getInt("is_file");
            if(is_file==1)
            {
                e.setIs_file(1);
                e.setFile_id(resultSet.getString("file_id"));
                e.setFile_name(resultSet.getString("file_name"));
            }
            else e.setIs_file(0);
            System.out.println("找到了"+e.getSender()+" to "+e.getReceiver()+" "+e.getIs_file());
            massagelist.add(e);
        }
        Collections.reverse(massagelist);
        Conn.close();
        return massagelist;
    }
}
